package com.leyou.gateway.scheduled;

import com.leyou.client.auth.AuthClient;
import com.leyou.gateway.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 定时获取服务Token的任务类
 */
@Component
@Slf4j
public class AppTokenScheduler {

    @Autowired
    private AuthClient authClient;
    @Autowired
    private JwtProperties jwtProps;

    private String appToken;//存储服务token变量

    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L; //24小时

    /**
     * token获取失败后重试的间隔
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;


    /**
     * 定时获取服务token
     *  需求：每隔24小时获取1次
     */
    @Scheduled(fixedRate = TOKEN_REFRESH_INTERVAL)
    public void autoGetAppToken(){
        //注意： 如果远程获取token失败了，隔10秒重试，直到成功为止

        //1.远程调用授权中心获取token的方法
        while(true) {
            try {
                String serviceName = jwtProps.getApp().getServiceName();
                String appToken = authClient.authorization(serviceName, jwtProps.getApp().getSecret());

                this.appToken = appToken;//把获取到服务token赋值给成员变量

                log.info("【服务token定时获取】"+serviceName+"：服务token获取成功");

                //退出
                break;
            } catch (Exception e) {

                log.error("【服务token定时获取】获取服务token失败，"+TOKEN_RETRY_INTERVAL+"后重试!");
                //10秒后重试
                try {
                    Thread.sleep(TOKEN_RETRY_INTERVAL);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }

            }
        }

    }

    public String getAppToken() {
        return appToken;
    }
}
